package com.quan.mall.service.impl;

import com.quan.commons.core.biz.support.MyBaseServiceImpl;
import com.quan.commons.core.utils.PageUtils;
import com.quan.mall.commons.constant.MallProductConstant;
import com.quan.mall.commons.vo.PmsAttrGroupVo;
import com.quan.mall.entity.PmsAttrAttrgroupRelation;
import com.quan.mall.entity.PmsAttrGroup;
import com.quan.mall.entity.PmsCategory;
import com.quan.mall.service.PmsAttrAttrgroupRelationService;
import com.quan.mall.service.PmsAttrGroupService;
import com.quan.mall.service.PmsCategoryService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;

import com.quan.mall.commons.vo.PmsAttrVo;
import com.quan.mall.entity.PmsAttr;
import com.quan.mall.mapper.PmsAttrMapper;
import com.quan.mall.service.PmsAttrService;


@Slf4j
@Service
public class PmsAttrServiceImpl extends MyBaseServiceImpl<PmsAttrMapper, PmsAttr> implements PmsAttrService {

    @Autowired
	private PmsAttrMapper mapper;

    @Autowired
    private PmsCategoryService pmsCategoryService;

    @Autowired
    private PmsAttrAttrgroupRelationService pmsAttrAttrgroupRelationService;

    @Autowired
    private PmsAttrGroupService pmsAttrGroupService;

	@Override
    public List<PmsAttrVo> queryList(PageUtils pageUtils, PmsAttrVo vo) {
        QueryWrapper<PmsAttr> queryWrapper = new QueryWrapper<PmsAttr>(vo);

        List<PmsAttr> list = super.list(pageUtils, queryWrapper);
        List<PmsAttrVo> collect = list.stream().map(item -> {
            PmsAttrVo bean = new PmsAttrVo();
            BeanUtils.copyProperties(item, bean);
            return bean;
        }).collect(Collectors.toList());

        return collect;
    }

    @Override
    public PageUtils queryPage(PageUtils pageUtils, PmsAttrVo vo) {
        QueryWrapper<PmsAttr> queryWrapper = new QueryWrapper<PmsAttr>(vo);

        if(StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("attr_name", vo.getKeyword());
            });
        }

        final IPage<PmsAttr> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<PmsAttr> records = page.getRecords();

        final List<PmsAttr> collect = records.stream().map((item) -> {
            PmsAttrVo bean = new PmsAttrVo();
            BeanUtils.copyProperties(item, bean);

            PmsCategory category = pmsCategoryService.getById(bean.getCateId());
            if (category != null) {
                bean.setCategoryName(category.getName());
            }

            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }


    @Override
    public PageUtils queryAttrPage(PageUtils pageUtils, String attrType, PmsAttrVo vo) {
        QueryWrapper<PmsAttr> queryWrapper = new QueryWrapper<PmsAttr>(vo);

        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? MallProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : MallProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());

        if(StringUtils.isNotBlank(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("attr_name", vo.getKeyword());
            });
        }

        final IPage<PmsAttr> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        final List<PmsAttr> records = page.getRecords();

        final List<PmsAttr> collect = records.stream().map((item) -> {
            PmsAttrVo bean = new PmsAttrVo();
            BeanUtils.copyProperties(item, bean);

            PmsCategory category = pmsCategoryService.getById(bean.getCateId());
            if (category != null) {
                bean.setCategoryName(category.getName());
            }

            return bean;
        }).collect(Collectors.toList());

        ps.setRecords(collect);
        return ps;
    }

    @Override
    public PmsAttrVo getAttrInfo(Long id) {
        //查询详细信息
        PmsAttr attrEntity = super.getById(id);

        PmsAttrVo vo = new PmsAttrVo();
        BeanUtils.copyProperties(attrEntity, vo);

        // 设置分类信息
        Long cateId = attrEntity.getCateId();
        Long[] categoryPath = pmsCategoryService.findCategoryPath(cateId);

        vo.setCategoryPath(categoryPath);
        PmsCategory categoryEntity = pmsCategoryService.getById(cateId);
        if (categoryEntity != null) {
            vo.setCategoryName(categoryEntity.getName());
        }

        return vo;
    }

    @Override
    public List<PmsAttr> getGroupAttrs(Long attrgroupId) {
        List<PmsAttrAttrgroupRelation> entities = pmsAttrAttrgroupRelationService.list
                (new QueryWrapper<PmsAttrAttrgroupRelation>().eq("attr_group_id", attrgroupId));

        List<Long> attrIds = entities.stream().map((attr) -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        //如果attrIds为空就直接返回一个null值出去
        if (attrIds == null || attrIds.size() == 0) {
            return null;
        }

        final List<PmsAttr> pmsAttrs = super.listByIds(attrIds);

        return pmsAttrs;
    }

    @Override
    public void deleteRelation(PmsAttrGroupVo[] vos) {
        final List<PmsAttrGroupVo> pmsAttrGroupRelationVos = Arrays.asList(vos);
        for (PmsAttrGroupVo pmsAttrGroupRelationVo : pmsAttrGroupRelationVos) {
            QueryWrapper<PmsAttrAttrgroupRelation> queryWrapper = new QueryWrapper<PmsAttrAttrgroupRelation>();
            queryWrapper.eq("attr_id", pmsAttrGroupRelationVo.getAttrId());
            queryWrapper.eq("attr_group_id", pmsAttrGroupRelationVo.getGroupId());
            this.pmsAttrAttrgroupRelationService.remove(queryWrapper);
        }
    }

    @Override
    public PageUtils getNoRelationAttr(PageUtils pageUtils, Long attrgroupId, PmsAttrVo vo) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        PmsAttrGroup attrGroupEntity = pmsAttrGroupService.getById(attrgroupId);
        //获取当前分类的id
        Long cateId = attrGroupEntity.getCateId();

        //2、当前分组只能关联别的分组没有引用的属性
        //2.1）、当前分类下的其它分组
        List<PmsAttrGroup> groupEntities = pmsAttrGroupService.list(new QueryWrapper<PmsAttrGroup>().eq("cate_id", cateId));
        System.out.println(cateId);

        //获取到所有的attrGroupId
        List<Long> collect = groupEntities.stream().map((item) -> {
            return item.getId();
        }).collect(Collectors.toList());

        //2.2）、这些分组关联的属性
        List<PmsAttrAttrgroupRelation> groupId = this.pmsAttrAttrgroupRelationService.list
                (new QueryWrapper<PmsAttrAttrgroupRelation>().in("attr_group_id", collect));

        List<Long> attrIds = groupId.stream().map((item) -> {
            return item.getAttrId();
        }).collect(Collectors.toList());


        //2.3）、从当前分类的所有属性移除这些属性
        QueryWrapper<PmsAttr> queryWrapper = new QueryWrapper<PmsAttr>()
                .eq("cate_id", cateId)
                .eq("attr_type", MallProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());

        if (attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("id", attrIds);
        }

        // 模糊查询
        if (StringUtils.isNotEmpty(vo.getKeyword())) {
            queryWrapper.and(w -> {
                w.like("attr_name", vo.getKeyword());
            });
        }

        final IPage<PmsAttr> page = super.selectPage(pageUtils, queryWrapper);

        PageUtils ps = new PageUtils(page);

        return ps;
    }
}